var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var bodyParser = require('body-parser');
var multer = require('multer');

var session = require('express-session');

var app = express();
/**
 * ====================引入路由====================
 */
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login');

/**
 * ====================指定渲染模板========================
 */
app.set('views', path.join(__dirname, 'pages'));
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');
// app.set('view engine', 'ejs');
app.set('view engine', 'html');
app.engine( '.html', require( 'ejs' ).__express );

/**
 * 中间件
 * ====================处理解析Post========================
 */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(multer());



// app.use(logger('dev'));
// app.use(express.json());
// app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser());

/**
 * ====================提供静态文件====================
 * express.static —— 指定静态文件的查找目录【内置中间件】
 * 相对于你启动 node 进程的目录
 * path.join(__dirname, 'public') 绝对路径
 * __dirname， 当前运行的js文件所在的目录，绝对路径
 */
// app.use('/static', express.static(path.join(__dirname, 'public'))) //指定前缀
app.use(express.static(path.join(__dirname, 'public')));

/**
 * ====================路由控制====================
 */
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);

/**
 * ====================页面访问控制====================
 */
app.use(session({
  secret:'secret',
  resave:true,
  saveUninitialized:false,
  cookie:{
      maxAge:1000*60*10  //过期时间设置(单位毫秒)
  }
}));

app.use(function(req, res, next){
  //res.locals对象保存在一次请求范围内的响应体中的本地变量值
  res.locals.user = req.session.user; 
  var err = req.session.error;
  res.locals.message = '';
  if (err) res.locals.message = '<div style="margin-bottom: 20px;color:red;">' + err + '</div>';
  next();
});

/**
 * ====================错误处理====================
 */
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


/**
 * ====================http请求处理====================
 */
app.post('/login', function (req, res) {
  var user = {
    username: 'admin',
    password: 'admin',
  };
  if (req.body.username == user.username && req.body.password == user.password) {
    res.send(200);
  } else {
    res.send(404);
  }
});

module.exports = app;
